<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/*******************
***  Ebay远程订单同步处理
***  
*** 2017/08/06
**********/
class Ebaydata_Remote
{
	
	function __construct()
	{    
		 $this->CI =& get_instance();
        $this->db1 = $this->CI->load->database('default', TRUE);
        $this->db2 = $this->CI->load->database('amazondata', TRUE);
		$this->CI->load->library('Amazondata');
        $this->amazondata=new amazondata();
	}
	
	public function GetEbayInsertOrder()
	{
		
		$row = $this->db2->get_where("db_ebayorder","is_updata=0 ")->result_array();
		if(count($row)==0)
		{
			return false;
		}

		foreach ($row as $v){
		//核对sku
	if (empty($v['PaidTime'])) {

		  $sql="delete from db_ebayorder where e_id = ".$v['e_id'];
		  $this->db2->query($sql);
		continue;
	}
	if ($v['OrderStatus']=='Cancelled') {
	$this->db2->update("db_ebayorder",array("is_updata"=>'1'),"e_id=".$v['e_id']);
	continue;
	}
		$TransactionArray = json_decode($v['TransactionArray'],true);
		$ShippingDetails = json_decode($v['ShippingDetails'],true);
		$MonetaryDetails=json_decode($v['MonetaryDetails'],true);
		$transat=$TransactionArray['Transaction'];


	$TransactionID=(isset($transat['TransactionID'])?$transat['TransactionID']:$transat[0]['TransactionID']);
	if(!isset($transat['TransactionID']))
	{
		unset($transat);
		$transat=$TransactionArray['Transaction'][0];
	}

	$skuarr=array();

	if (isset($TransactionArray['Transaction'][0])) {
		$skui=count($TransactionArray['Transaction']);
		for ($i=0; $i <$skui ; $i++) {
			$skuarr[]= isset($TransactionArray['Transaction'][$i]['Variation']['SKU'])?$TransactionArray['Transaction'][$i]['Variation']['SKU']:$TransactionArray['Transaction'][$i]['Item']['SKU'];
		}
	}else{
		 $skuarr[]= isset($TransactionArray['Transaction']['Variation']['SKU'])?$TransactionArray['Transaction']['Variation']['SKU']:$TransactionArray['Transaction']['Item']['SKU'];
	}


  foreach ($skuarr as $key=>$sku) {
    $check=$this->db1->get_where("db_goods","goods_sku='{$sku}'")->result_array();      
	if (empty($check)) {
			$checklist=$this->db1->get_where("db_goods","cognatelist like '%,{$sku},%'")->result_array();
			if(empty($checklist)){
				$Status=7;
				break;
			}else{
				$skuarr[$key]=$checklist[0]['goods_sku'];
				$Status=2;
			}
			if($Status==7){
				$checklist=$this->db1->get_where("db_salesku","autosku='".$sku."'")->result_array();
				if(!empty($checklist)){
					$skuarr[$key]=$checklist[0]['goods_sku'];
					$Status=2;
				}
			}
	}else{
		$Status=2;
	 }
   }
 

			$shopid=$v['shopid'];
			$ShippingAddress=json_decode($v['ShippingAddress'],true);

			//查询订单是否已被导入
			$rorder = $this->db1->get_where("db_order_list","tradeid='".$ShippingDetails['SellingManagerSalesRecordNumber']."' AND shopid='".$shopid."'")->result_array();
			if(count($rorder)==1)
			{
				$this->db2->update("db_ebayorder",array("is_updata"=>'1'),"e_id=".$v['e_id']);
				continue;
			}
           //获取信息准备导入。
	
            $postdata="";
			$postdata["order_sn"] = $this->amazondata->getNo('ebay',$TransactionID,$shopid);
			$postdata["ebay_orderID"] =$v['OrderID'];
			$postdata["dates"] = date("Y-m-d");
			$postdata["order_status"] = $Status;
			$postdata["order_source"] ='正常订单';
			$postdata['shipping_status']=0;
			$postdata["customerid"] =addslashes(trim($v['BuyerUserID']));
			$postdata["consignee"] =addslashes(trim($ShippingAddress['Name']));
			$postdata["country"] = $ShippingAddress['CountryName'];
			$postdata["country_code"]= $ShippingAddress['Country'];
			$rscountry = $this->db1->get_where("d_chinaexpress","NAME='".$ShippingAddress['CountryName']."'")->result_array();
			if(isset($rscountry[0]["id"])){
				$postdata["country_cn"] = $rscountry[0]["FILED1"];
			}else{
				$postdata["country_cn"]='';
			}
			$phone = gettype($ShippingAddress['Phone'])=='string'?$ShippingAddress['Phone']:'';
			if($phone=='Invalid Request')
			{
				$phone = "";
			}
			$postdata["province"] = gettype($ShippingAddress['StateOrProvince'])=='string'?$ShippingAddress['StateOrProvince']:'';
			$postdata["city"] = gettype($ShippingAddress['CityName'])=='string'?$ShippingAddress['CityName']:'';
			$postdata["address"] = addslashes(trim(gettype($ShippingAddress['Street1'])=='string'?$ShippingAddress['Street1']:''));
			$postdata["address2"] = addslashes(trim(gettype($ShippingAddress['Street2'])=='string'?$ShippingAddress['Street2']:''));
			$postdata["zipcode"] = gettype($ShippingAddress['PostalCode'])=='string'?$ShippingAddress['PostalCode']:'';
			$postdata["tel"] = $phone;
			$postdata["mobile"] ='';
			$postdata["email"] = isset($transat['Buyer']['Email'])=='string'?$transat['Buyer']['Email']:'';
			$postdata["shopid"] = $shopid;
			$rshop = $this->db1->get_where("d_shop","id=".$shopid)->result_array();
			$postdata["shopname"] = $rshop[0]["name"];
			$postdata["shopoper"] = $rshop[0]["updateoper"];
			
			$postdata["moneytype"] =$v['currencyID'];
			$exchange=$this->db1->get_where("d_moneyrate","name='{$v['currencyID']}'")->result_array();
			$exchangerate=$exchange[0]["rate"];
			//$postdata["tradeid"] = $TransactionID;
			$postdata["tradeid"] = $ShippingDetails['SellingManagerSalesRecordNumber']?$ShippingDetails['SellingManagerSalesRecordNumber']:$TransactionID;
			
			if(count($ShippingDetails) ==count($ShippingDetails, 1))
			{
				$ShippingService = $ShippingDetails["ShippingService"];
			}else{
				$ShippingService = $ShippingDetails['ShippingServiceOptions'][0]['ShippingService'];
			}

			$postdata["postageservice"] = $ShippingService?$ShippingService:NULL;
			$postdata['shipping_id']='';
			$postdata['shipping_name']='';
			$postdata['shipping_time']='';
			$postdata["goods_originask"] =$v['Subtotal'];//订单原始金额
			$postdata["goods_amount"] =$v['Subtotal']*$exchangerate;//订单rmb
		    $ShippingServiceSelectedarr = json_decode($v['ShippingServiceSelected'],true);
			$postdata["shipping_fee"] = $ShippingServiceSelectedarr['ShippingServiceCost']*$exchangerate;//运费rmb
			$postdata["shipping_originask"] = $ShippingServiceSelectedarr['ShippingServiceCost'];//运费原始金额
			$postdata["add_time"] = time();
			$postdata["ordertime"] = date("Y-m-d H:i:s",strtotime($transat['CreatedDate']));
			$postdata["saleschannel"] = 'eBay';
			$postdata["pay_fee"] = $MonetaryDetails['Payments']['Payment']['FeeOrCreditAmount']*$exchangerate;
			$postdata['pack_fee']='';

			//平台费用
			if($rshop[0]["shop_platform_fee"]>0)
			{
				$shop_platform_fee  =$rshop[0]["shop_platform_fee"];
			}else{
				$shop_platform_fee = 0.15;
			}
			

			$postdata["platform_fee"] = $v['Subtotal']*$shop_platform_fee*$exchangerate;
			$postdata["surplus"]="";
			$postdata["paypalmail"]=isset($transat['Buyer']['Email'])?$transat['Buyer']['Email']:'';
			$postdata["platform_message"]=$v['BuyerCheckoutMessage'];
		    $postdata["payid"]=$MonetaryDetails['Payments']['Payment']['ReferenceID'];
		    $postdata["payaccount"]=$v['SellerEmail'];
			$postdata['platformID']  = $rshop[0]['platfrom'];//平台
			$postdata['moneyrate']  = $exchangerate;//汇率
		    //return $postdata;


		   
			$this->db1->trans_begin();
			try{
				$this->db1->insert("db_order_list",$postdata);
				$orderID = $this->db1->insert_id();
				$this->db2->update("db_ebayorder",array("is_updata"=>'1'),"e_id=".$v['e_id']);
				
				$factorycode =$this->amazondata->factorycode();
				$weight = 0;
				// foreach($sell as $key=>$res)
				// {
				$itemidi=0;
					foreach ($skuarr as $key =>$sku) {
					$rgoods = $this->db1->get_where("db_goods","goods_sku='".$sku."'")->result_array();
				$QuantityPurchased=isset($TransactionArray['Transaction'][$itemidi]['QuantityPurchased'])?$TransactionArray['Transaction'][$itemidi]['QuantityPurchased']:$TransactionArray['Transaction']['QuantityPurchased'];
					$TransactionPrice=isset($TransactionArray['Transaction'][$itemidi]['TransactionPrice'])?$TransactionArray['Transaction'][$itemidi]['TransactionPrice']:$TransactionArray['Transaction']['TransactionPrice'];

					if(isset($rgoods[0]["goods_id"]))
					{
						$goods_id = $rgoods[0]["goods_id"];
						$sweight =$QuantityPurchased* $rgoods[0]["g_weight"];
						$weight = $weight+$sweight;
						/*****************成本价计算方式********
						**  11、12开头定制的衣服按成本价计算
						**  批量的sku 按关联价计算
						**  外采购的衣服按成本价计算
						*********************************/
						if(is_numeric($sku) && preg_match('|^\d{8}$|',$sku))	//数字并且8位SKU并且11 12开头
						{
							$goodscode  = substr($sku,0,2);//取开头2位数
							if(in_array($goodscode,$factorycode))	//是否存在在工厂code
							{
								$costprice = $rgoods[0]["g_costprice"];	//定制衣服按成本价计算
							}
						}else{
							//如果当前SKU不是8位，查询父SKU是不是8位并且11，12开头
							if(is_numeric($rgoods[0]["goods_parent_sku"]) && preg_match('|^\d{8}$|',$rgoods[0]["goods_parent_sku"]))	//数字并且8位SKU并且11 12开头
							{
								$goodscodes  = substr($rgoods[0]["goods_parent_sku"],0,2);//取开头2位数
								if(in_array($goodscodes,$factorycode))	//是否存在在工厂code
								{
									$costprice = $rgoods[0]["bulkprice"];	//批量按关联价计算
								}
							}else{
								$costprice = $rgoods[0]["g_costprice"];
							}
						}
						



					}else{
						$goods_id = 0 ;
					}
					$postsell = "";
					$postsell["order_id"] = $orderID;
					$postsell["goods_id"] = $goods_id;
					$postsell["goods_name"] = addslashes(isset($TransactionArray['Transaction'][$itemidi]['Item']['Title'])?$TransactionArray['Transaction'][$itemidi]['Item']['Title']:$TransactionArray['Transaction']['Item']['Title']);
					$postsell["goods_sn"] =  $sku;
					$postsell["costprice"] =isset($costprice)?$costprice:'';
					$postsell["goods_number"] = $QuantityPurchased;
					$postsell["goods_price"] = $TransactionPrice*$exchangerate;
					$postsell["goods_weight"]=$sweight;
					$postsell["goods_amount"] = $QuantityPurchased* $TransactionPrice*$exchangerate;
					$postsell["originsellprice"] = isset($TransactionArray['Transaction'][$itemidi]['TransactionPrice'])?$TransactionArray['Transaction'][$itemidi]['TransactionPrice']:$TransactionArray['Transaction']['TransactionPrice'];
					$postsell["originsku"] = $sku;
					$postsell["product_link"]=isset($TransactionArray['Transaction'][$itemidi]['Item']['ItemID'])?$TransactionArray['Transaction'][$itemidi]['Item']['ItemID']:$TransactionArray['Transaction']['Item']['ItemID'];

					   unset($sale_remark);
		    $sale_remark='';
		    if(isset($TransactionArray['Transaction'][$itemidi]['Variation']['VariationSpecifics'])){
		    	$vvn =$TransactionArray['Transaction'][$itemidi]['Variation']['VariationSpecifics'];
		    	if (isset($TransactionArray['Transaction'][$itemidi]['Variation']['VariationSpecifics']['NameValueList'][0])) {
		    		$vvn =$TransactionArray['Transaction'][$itemidi]['Variation']['VariationSpecifics']['NameValueList'];
		    	}		    	
		    	foreach ($vvn as $value) {
	$sale_remark.=$value['Name'].'&nbsp'.$value['Value'].'&nbsp';
}
		    }
					$postsell["sale_remark"]=$sale_remark;
					$this->db1->insert("db_order_sell",$postsell);

					if($goods_id==0)
					{
						$this->db1->update("db_order_list",array("order_status"=>7),"order_id=".$orderID);
					}
					if($weight)
					{
						$this->db1->update("db_order_list",array("orderweight"=>$weight),"order_id=".$orderID);
					}
					$itemidi++;
				 }
                //更新日志
				$imgdata["goods_id"] = $orderID;	//订单ID
				$imgdata["updatetime"] = date("Y-m-d H:i:s");
				$imgdata["createUid"] = 0;
				$imgdata["types"] = 3;
				$imgdata["content"] = 'ebay接口自动新增订单,交易ID='.$TransactionID;
				$imgdata["createUser"] ='auto';
				$this->db1->query($this->db1->insert_string('db_goods_log', $imgdata));
				

				$this->db1->trans_commit();
			}catch (Exception $e){
				$this->db1->trans_rollback();
				$msg =  $e->getMessage();
				print_r($msg);exit;
			}


		 }


		
	}
	
	public function Ebayreturn()
		{
			$wisharr=$this->db1->get_where("d_shop","platfromname='ebay' AND  amazonkey !='' and agent_visit = 1")->result_array();
			foreach($wisharr as $key=>$value)
			{
				$shopname=$value['name'];
				$shopid=$value['id'];
				$listrow= $this->db1->get_where("db_order_list","shopid='{$shopid}'  and is_update_platform='0' AND shipping_number !='' and (order_status='4' or order_status='5') ")->result_array();
				if(count($listrow)>0)
				{
					foreach($listrow as $key=>$rs)
					{
						$shippingrow=$this->db1->get_where("db_order_express","id='". $rs["shipping_id"]."'")->result_array();
						$wish_express = $shippingrow[0]["wish_express"];
						
						$TransactionID=$rs['order_sn'];
					    $ItemID=substr($rs['ebay_orderID'],0,strpos($rs['ebay_orderID'],'-'));
						
						$iflk=substr($rs['shipping_number'],0,2);
						if ($iflk=='LK') {
							$this->db1->update("db_order_list",array("is_update_platform"=>'1'),"order_id=".$rs['order_id']);	//不再更新
						    continue;
						}

						$post="";
						$post["order_id"] = $rs["order_sn"];
						$post["tradeid"] = $rs["tradeid"];
						$post["shipping_id"] = $rs["shipping_id"];
						$post["shipping_number"] = $rs["shipping_number"];
						$post["shipping_name"] = $wish_express;
						$post["shopid"] = $rs["shopid"];
						$post["shopname"] = $rs["shopname"];
						$post["isupdate"] = 1;
						$post["updatetime"] = date("Y-m-d H:i:s");
						$post["shipping_time"] = date("Y-m-d H:i:s");
						$post["TransactionID"] = $TransactionID;
						$post["ItemID"] = $ItemID;

						$post["message"] ="等待更新到Ebay平台";
						$this->db2->insert("db_eBay_update",$post);

						$this->db1->update("db_order_list",array("is_update_platform"=>'1'),"order_id=".$rs['order_id']);	//不再更新
						$log='';
						$log['orderId']=$rs['order_id'];
						$log['updateTime']=date('Y-m-d H:i:s');
						$log['shippingName']=$wish_express;
						$log['shippingNumber']=$rs["shipping_number"];
						$log['types']='wish';
						$log['content']='自动同步物流信息'.$response;
						$this->db1->insert("db_onlineshop_log",$log);
						$imgdata = "";
						$imgdata["goods_id"] = $rs['order_id'];	//订单ID
						$imgdata["updatetime"] = date("Y-m-d H:i:s");
						$imgdata["createUid"] = 0;
						$imgdata["types"] = 3;
						$imgdata["content"] = '自动同步物流信息,物流名称'.$wish_express.'物流单号='.$rs["shipping_number"];
						$imgdata["createUser"] ='auto';
						$this->db1->query($this->db1->insert_string('db_goods_log', $imgdata));
					}
				}
			}
			
		}
	
























}


?>